import {defineStore} from 'pinia'
// @ts-ignore
import Utils from "@/vue2-flow/src/utils/Common";
// @ts-ignore
import FlowRuntimeApi from '../../../api/flow/FlowRuntimeApi.js'
// @ts-ignore
import SysDriveApi from "@/api/flow/SysDriveApi.js";
import {FlowInfoType} from "@/utils";
import {FlowApi} from "@/api/FlowApi";
import {Device} from "@/api/DeviceApi";
import {AppParams} from "@/utils/appParams";
import {NodeApi} from "@/api/NodeApi";

interface LoggerType {
    [key: number]: []
}

export const useFlowStore = defineStore({
    id: 'useFlowStore',
    state: () => ({
        CurrentFlow: {}, // 流程的基本信息，执行之后会包含流程的所有信息
        CurrentClickNode: {} as any, // 当前点击的节点
        AllFlow: [] as FlowInfoType[], // 所有流程信息
        Device: [], // 所有设备
        NodeGroup: [], // 所有节点,节点库
        PlcAddress: [], // PLC地址
        GlobalParams: {}, // 全局变量
        LoggerFlow: [] as [], // 流程日志
        StopLoadingLogger: true, // 暂停/播放
    }),
    actions: {
        /**
         * 当前流程被点击时，保存点击的流程
         * @param Node
         * @constructor
         */
        SetCurrentClickNode(Node: any) {
            this.CurrentClickNode = Node
        },
        /**
         * 设置当前流程
         * @param Flow
         * @constructor
         */
        SetCurrentFlow(Flow: any) {
            this.CurrentFlow = Flow
        },

        /**
         * 加载所有流程信息，并缓存到本地
         *
         * 初始化加载时，没有当前流程则取第一个后，设置当前流程
         * @constructor
         */
        SetAllFlow() {
            FlowApi.Gets().then((res) => {
                this.AllFlow = res.Data
                if (Utils.IsEmpty(this.CurrentFlow)) {
                    this.SetCurrentFlow(res.Data[0])
                }
            });
        },

        /**
         * 更新设备列表
         * @constructor
         */
        UpdateDevice(Callback: Function) {
            Device.Gets().then(res => {
                if (res.IsSuccess) {
                    this.Device = res.Data
                    Callback && Callback(res)
                }
            })
        },

        SetNodeGroup(Callback: Function) {
            NodeApi.Gets().then(res => {
                this.NodeGroup = res.Data.groups
                Callback && Callback(res.Data.groups)
            });
        },

        UpdatePlcAddress(Callback: Function) {
            Device.GetPlcAddress(AppParams.DRIVER_TYPE_PLC).then(res => {
                this.PlcAddress = res.Data;
                Callback && Callback(res.Data)
            })
        },

        SetGlobalParams(GlobalParams: object) {
            this.GlobalParams = GlobalParams
        },

        /**
         * 更新日志
         * @param NodeLogger
         * @constructor
         */
        UpdateLogger(NodeLogger: any) {
            if (!this.StopLoadingLogger) {
                return
            }
            if (this.LoggerFlow.length > 220) {
                this.LoggerFlow = []
            }
            switch (NodeLogger.Level) {
                case 'Warning':
                    NodeLogger.className = 'logger-warning';
                    break;
                case 'Error':
                    NodeLogger.className = 'logger-error';
                    break;
                case 'Complete':
                    NodeLogger.className = 'logger-complete';
                    break;
            }
            this.LoggerFlow.push(NodeLogger)
        },
        ClearLogger(NodeId?: number) {
            let index;
            if (NodeId) {
                while ((index = this.LoggerFlow.findIndex(log => log.NodeId === NodeId)) !== -1) {
                    this.LoggerFlow.splice(index, 1);
                }
            } else {
                this.LoggerFlow = []
            }
        },
        StopLoading(Val?: boolean) {
            if (Val != undefined) {
                this.StopLoadingLogger = Val
            } else {
                this.StopLoadingLogger = !this.StopLoadingLogger
            }
        }
    },
    getters: {
        GetDevice: (state) => {
            return (Type: string) => {
                return state.Device.filter((d: any) => d.DeviceType === Type)
            }
        },
        GetLogger: (state) => (NodeId: number) => {
            let NodeLogs = state.LoggerFlow.filter(log => log.NodeId === NodeId) || []
            return NodeLogs.sort((a, b) => {
                // 将时间字符串转换为Date对象
                const timeA = new Date(a.Time);
                const timeB = new Date(b.Time);

                // 比较时间，返回差值
                return timeA - timeB;
            }).reverse();
        }
    }
})
